#!/bin/bash

RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
PLAIN='\033[0m'

red() {
    echo -e "\033[31m\033[01m$1\033[0m"
}

green() {
    echo -e "\033[32m\033[01m$1\033[0m"
}

yellow() {
    echo -e "\033[33m\033[01m$1\033[0m"
}

REGEX=("debian" "ubuntu" "centos|red hat|kernel|oracle linux|alma|rocky" "'amazon linux'" "fedora" "alpine")
RELEASE=("Debian" "Ubuntu" "CentOS" "CentOS" "Fedora" "Alpine")
PACKAGE_UPDATE=("apt-get update" "apt-get update" "yum -y update" "yum -y update" "yum -y update" "apk update -f")
PACKAGE_INSTALL=("apt -y install" "apt -y install" "yum -y install" "yum -y install" "yum -y install" "apk add -f")
PACKAGE_UNINSTALL=("apt -y autoremove" "apt -y autoremove" "yum -y autoremove" "yum -y autoremove" "yum -y autoremove" "apk del -f")

[[ $EUID -ne 0 ]] && red "注意：请在root用户下运行脚本" && exit 1

CMD=("$(grep -i pretty_name /etc/os-release 2>/dev/null | cut -d \" -f2)" "$(hostnamectl 2>/dev/null | grep -i system | cut -d : -f2)" "$(lsb_release -sd 2>/dev/null)" "$(grep -i description /etc/lsb-release 2>/dev/null | cut -d \" -f2)" "$(grep . /etc/redhat-release 2>/dev/null)" "$(grep . /etc/issue 2>/dev/null | cut -d \\ -f1 | sed '/^[ ]*$/d')")

for i in "${CMD[@]}"; do
    SYS="$i" && [[ -n $SYS ]] && break
done

for ((int = 0; int < ${#REGEX[@]}; int++)); do
    if [[ $(echo "$SYS" | tr '[:upper:]' '[:lower:]') =~ ${REGEX[int]} ]]; then
        SYSTEM="${RELEASE[int]}" && [[ -n $SYSTEM ]] && break
    fi
done

[[ -z $SYSTEM ]] && red "不支持当前VPS系统, 请使用主流的操作系统" && exit 1

# 检测 VPS 处理器架构
archAffix() {
    case "$(uname -m)" in
        x86_64 | amd64) echo 'amd64v1' ;;
        armv8 | arm64 | aarch64) echo 'arm64' ;;
        s390x) echo 's390x' ;;
        *) red "不支持的CPU架构!" && exit 1 ;;
    esac
}

# 安装 Bot Agent
install_agent(){
    # 检测是否为CentOS，如不是则执行软件包更新
    [[ ! $SYSTEM == "CentOS" ]] && ${PACKAGE_UPDATE[int]}

    # 安装常用组件
    ${PACKAGE_INSTALL[int]} curl wget sudo tar

    # 创建 Bot Agent 程序目录
    mkdir /opt/OracleAgent

    # 下载 Bot Agent
    cd /opt/OracleAgent
    last_ver=$(curl -Ls "https://gitlab.com/api/v4/projects/Misaka-blog%2Foci-bot/releases" | grep -oP '"tag_name":"v\K[^\"]+' | head -n 1)
    wget -N https://gitlab.com/Misaka-blog/oci-bot/-/releases/v"$last_ver"/downloads/OracleAgent_"$last_ver"_linux_$(archAffix).tar.gz
    tar -xzvf OracleAgent_"$last_ver"_linux_$(archAffix).tar.gz
    rm -f OracleAgent_"$last_ver"_linux_$(archAffix).tar.gz README.md LICENSE
    rm -rf systemd
    
    # 授予可执行权限
    chmod +x /opt/OracleAgent/OracleAgent

    # 检查 parem 是否存在值，如没有则询问用户配置
    if [[ -n $1 ]]; then
        while [ $# -gt 0 ]; do
            case $1 in
                --id )
                    botid=$2
                    shift
                    ;;
                --secret )
                    secret=$2
                    shift
                    ;;
            esac
            shift
        done
    else
        yellow "请根据引导提示，设置 Bot Agent"
        read -rp "请输入从 Bot 获取到的 ID：" botid
        read -rp "请输入从 Bot 获取到的 Secret：" secret
    fi

    # 写入 Agent 配置及 Systemd 服务文件
    cat <<EOF > /etc/systemd/system/OracleAgent.service
[Unit]
Description=OracleAgent service
After=network.target
Documentation=https://gitlab.com/Misaka-blog/oci-bot

[Service]
WorkingDirectory=/opt/OracleAgent/
ExecStart=/opt/OracleAgent/OracleAgent --id $botid --secret $secret
Environment="LOG_LEVEL=verbose"
RemainAfterExit=yes
Restart=always

[Install]
WantedBy=multi-user.target
EOF

    # 应用 Systemd 服务文件
    systemctl daemon-reload

    # 下载脚本文件
    wget https://gitlab.com/Misaka-blog/oci-bot/-/raw/main/script.sh -O bot.sh

    # 提示用户配置
    yellow "请根据文档指示，设置 Bot Agent"
    green "然后使用本脚本启动即可"
}

uninstall_agent(){
    # 停止并禁用 Bot Agent 服务
    systemctl stop OracleAgent
    systemctl disable OracleAgent

    # 移除程序目录及 Systemd 服务文件
    rm -rf /opt/OracleAgent
    rm -f /lib/systemd/system/OracleAgent.service
}

start_agent(){
    systemctl start OracleAgent
    systemctl enable OracleAgent
}

stop_agent(){
    systemctl stop OracleAgent
    systemctl disable OracleAgent
}

edit_config(){
    echo ""
}

menu(){
    clear
    echo "#############################################################"
    echo -e "#                ${RED}OCI Bot Agent 一键安装脚本${PLAIN}               #"
    echo -e "# ${GREEN}作者${PLAIN}: MisakaNo の 小破站                                  #"
    echo -e "# ${GREEN}博客${PLAIN}: https://www.misaka.rest                             #"
    echo -e "# ${GREEN}GitHub 项目${PLAIN}: https://github.com/Misaka-blog               #"
    echo -e "# ${GREEN}GitLab 项目${PLAIN}: https://gitlab.com/Misaka-blog               #"
    echo -e "# ${GREEN}Telegram 频道${PLAIN}: https://t.me/misakanocchannel              #"
    echo -e "# ${GREEN}Telegram 群组${PLAIN}: https://t.me/misakanoc                     #"
    echo -e "# ${GREEN}YouTube 频道${PLAIN}: https://www.youtube.com/@misaka-blog        #"
    echo "#############################################################"
    echo ""
    echo -e " ${GREEN}1.${PLAIN} 安装 OCI Bot Agent"
    echo -e " ${GREEN}2.${PLAIN} 卸载 OCI Bot Agent"
    echo " -------------"
    echo -e " ${GREEN}3.${PLAIN} 启动 OCI Bot Agent"
    echo -e " ${GREEN}4.${PLAIN} 停止 OCI Bot Agent"
    echo -e " ${GREEN}5.${PLAIN} 重载 OCI Bot Agent"
    echo " -------------"
    echo -e " ${GREEN}6.${PLAIN} 修改 OCI Bot Agent 配置"
    echo " -------------"
    echo -e " ${GREEN}0.${PLAIN} 退出"
    echo ""
    read -rp " 请输入选项 [0-6] ：" answer
    case $answer in
        1 ) install_agent ;;
        2 ) uninstall_agent ;;
        3 ) start_agent ;;
        4 ) stop_agent ;;
        5 ) stop_agent && start_agent ;;
        6 ) edit_config ;;
        * ) red "请输入正确的选项 [0-6]！" && exit 1 ;;
    esac
}

if [[ -n $1 ]]; then
    install_agent $1 $2 $3 $4
else
    menu
fi